<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\BaseApiController;
use App\Models\LoveMember;
use App\Models\BreedUserCoin;
use App\Models\BreedConsume;
use Illuminate\Support\Facades\DB;

class UserBalanceController extends BaseApiController
{
    /**
     * 获取用户余额（茶包和沐浴露）
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserBalances()
    {
        \Log::info('[获取用户余额] ========== 开始获取 ==========');
        
        // 从 param 对象中获取参数
        $param = request()->input('param');
        $userId = $param['user_id'] ?? 0;
        
        \Log::info('[获取用户余额] 用户ID:', ['user_id' => $userId]);
        
        if (!$userId) {
            return response()->json([
                'code' => 400,
                'message' => '缺少用户ID参数',
                'data' => null
            ]);
        }
        
        try {
            // 1. 查询茶包余额（从 ims_yz_love_member 表）
            $teaBagBalance = 0;
            $loveMember = LoveMember::where('member_id', $userId)->first();
            if ($loveMember) {
                $teaBagBalance = $loveMember->usable ?? 0;
            }
            
            \Log::info('[获取用户余额] 茶包余额:', ['balance' => $teaBagBalance]);
            
            // 2. 查询沐浴露余额（从 ims_yz_breed_user_coin 表）
            // 需要累加所有支持置换的沐浴露类型
            $showerGelBalance = 0;
            
            // 先查出设置的支持哪种沐浴露（is_swap=1 表示支持置换）
            $breedConsumes = BreedConsume::where('is_swap', 1)->get();
            \Log::info('[获取用户余额] 支持置换的沐浴露类型:', ['types' => $breedConsumes->pluck('id')]);
            
            // 累加用户所有类型的沐浴露数量
            foreach ($breedConsumes as $breedConsume) {
                $record = BreedUserCoin::where([
                    'user_id' => $userId,
                    'consume_type' => $breedConsume->id
                ])->first();
                
                if ($record) {
                    $showerGelBalance += $record->num ?? 0;
                }
            }
            
            \Log::info('[获取用户余额] 沐浴露余额:', ['balance' => $showerGelBalance]);

            // 3. 查询额度（ims_yz_breed_user_coin_quota + ims_hhm_coin_corp_quota，两表累计）
            $breedQuota = DB::table('ims_yz_breed_user_coin_quota')
                ->where('user_id', $userId)
                ->value('num') ?? 0;

            $corpQuota = 0;
            $storeIds = DB::table('ims_yz_store')
                ->where('uid', $userId)
                ->pluck('id');

            if ($storeIds->isNotEmpty()) {
                $corpQuota = DB::table('ims_hhm_coin_corp_quota')
                    ->whereIn('store_id', $storeIds)
                    ->where('status', 2)    // 已审核通过
                    ->where('switch', 1)    // 已启用
                    ->sum('stock_num');
            }

            $creditRingBalance = (float) $breedQuota + (float) $corpQuota;

            \Log::info('[获取用户余额] 额度余额:', [
                'breed_quota' => $breedQuota,
                'corp_quota' => $corpQuota,
                'total' => $creditRingBalance
            ]);
            
            // 4. 返回结果
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => [
                    'tea_bag_balance' => (float) $teaBagBalance,        // 茶包余额
                    'shower_gel_balance' => (float) $showerGelBalance,  // 沐浴露余额
                    'credit_ring_balance' => (float) $creditRingBalance, // 额度余额
                    'user_id' => $userId
                ]
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[获取用户余额] ========== 查询失败 ==========', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '查询余额失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
}

